//
//  PictureSelectorController.swift
//  SinaWeiBo
//
//  Created by tuyue on 16/3/18.
//  Copyright © 2016年 xueyang.co.ltd. All rights reserved.
//

import UIKit
import SnapKit


private let PictureCellId2 = "PictureCellId2"

private let pictureCellMargin:CGFloat = 5

private let coloumImageCount:CGFloat = 4

private let maxImageCount = 3

class PictureSelectorController: UICollectionViewController {
    
    /**实例化一个可变数组 用于保存所选择的图片*/
    var imageList = [UIImage]()
    
    //MARK: - 重写构造方法
    init(){
    let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = pictureCellMargin
        layout.minimumLineSpacing = pictureCellMargin
        layout.sectionInset = UIEdgeInsets(top: pictureCellMargin, left: pictureCellMargin, bottom: 0, right: pictureCellMargin)
        let w  = (ScreenWidth - (coloumImageCount+1) * pictureCellMargin) / coloumImageCount
        layout.itemSize = CGSize(width: w, height: w)
        
        super.init(collectionViewLayout: layout)
        self.collectionView?.backgroundColor = UIColor.whiteColor()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: PictureCellId2)

        // Do any additional setup after loading the view.
    }

   
}


//MARK: - CollectionView的数据源方法
extension PictureSelectorController{
    
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let delta = imageList.count == maxImageCount ? 0 : 1
        return imageList.count + delta
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellId2, forIndexPath: indexPath) as! PictureSelectorCell
        //设置协议代理
        cell.selectorDelegate = self
        cell.backgroundColor = UIColor.randomColor()
        
        if indexPath.item == imageList.count{
            
        cell.image = nil
            
        }else {
            
        cell.image = imageList[indexPath.item]
            
        }
        return cell
    }
    
}





//MARK: - 声明协议 ：图片选择器，协议中规定必须实现的代理方法
protocol PictureSelectorCellDelegate : NSObjectProtocol{
     //用户将要选择图片
    func userWillChoosePicture()
    //用户将要删除所选择的图片
    func userWillDeletePicture(cell:PictureSelectorCell)
}



//MARK: - 遵守协议
//实现协议方法
extension PictureSelectorController: PictureSelectorCellDelegate {
    
    //用户将要选择图片
    func userWillChoosePicture() {
      //实例化图片选择类的对象
        let picker = UIImagePickerController()
        //设置图片选择器的代理
        picker.delegate = self
        //设置图片允许编辑，上传用户头像的时候可用
       // picker.allowsEditing = true
        //跳转图片选择界面
        presentViewController(picker, animated: true, completion: nil)
        
    }
    
    //用户将要删除图片
    func userWillDeletePicture(cell: PictureSelectorCell) {
        //确定要删除哪一张照片
        //1，根据用户传来的哪一个cell
        
        //根据cell获取点击的indexPath
        if let indexPath = collectionView?.indexPathForCell(cell) {
          //将用户选中的item从数组中移除
         imageList.removeAtIndex(indexPath.item)
            //刷新collectionView
            collectionView?.reloadData()
        }
    }
    
}


//MARK: - 实现图片选择器的代理方法
extension PictureSelectorController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    /**一旦实现这个方法后 图片选择器消失的权利就交给了程序员*/
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //将选择的照片添加到用于保存所选图片的数组
        imageList.append(image)
        //刷新collectionView
        collectionView?.reloadData()
        //销毁当前控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    

}

//MARK: - 创建PictureSelectorCell类
class PictureSelectorCell:UICollectionViewCell {
    //MARK: - 创建协议对象
    weak var selectorDelegate : PictureSelectorCellDelegate?
    
    /**创建image变量，并给这个变量设置赋值完后要做的，当这个属性被复制后，紧着着把这个值赋给Btn*/
    var image:UIImage? {
        didSet{
            //当image为nil的时候隐藏deleteBtn
            deleteBtn.hidden = image == nil
            //当image 有值后赋给addBtn
            addBtn.setImage(image, forState: .Normal)
        }
    }
    
    //点击addBtn后调取的方法
    @objc private func addBtnClick(){
        if image == nil {
            //遵守cell中协议的代理调取代理中将要选择图片的方法
            selectorDelegate!.userWillChoosePicture()
        }
        
    }
     //点击deleteBtn后调取的方法
    @objc private func deleteBtnClick(){
        //遵守cell中协议的代理调取代理中将要删除图片的方法
        selectorDelegate!.userWillDeletePicture(self)
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    /**默认实现报错*/
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /**setupUI*/
    func setupUI(){
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.right.equalTo(contentView)
        }
        
        //MARK: - 给按钮添加点击事件
        addBtn.addTarget(self, action: "addBtnClick", forControlEvents: .TouchUpInside)
        
        deleteBtn.addTarget(self, action: "deleteBtnClick", forControlEvents: .TouchUpInside)
        
    }
    
    //MARK: - 懒加载创建按钮
    private var addBtn:UIButton = UIFactory.factoryButtonWithImage(nil, backImageName: "compose_pic_add")
    private var deleteBtn:UIButton = UIFactory.factoryButtonWithImage(nil, backImageName: "compose_photo_close")
}

